package com.yokead.controller.oper;

import cn.jiangzeyin.StringUtil;
import cn.jiangzeyin.common.JsonMessage;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.yokead.common.OrderBaseControl;
import com.yokead.common.interceptor.NotLogin;
import com.yokead.service.order.ProductService;
import com.yokead.system.log.LogType;
import com.yokead.system.log.SystemLog;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.io.IOException;

/**
 * Created by jiangzeyin on 2017/6/22.
 */
@Controller
@RequestMapping("oper")
public class OperLoginControl extends OrderBaseControl {

    @RequestMapping(value = "login.html", method = RequestMethod.GET, produces = MediaType.TEXT_HTML_VALUE)
    @NotLogin
    public String login() {
        return "oper/login";
    }

    @Resource
    private ProductService productService;

    @RequestMapping(value = "loginOk", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ResponseBody
    @NotLogin
    public String loginOk(String key, String pwd, String name) {
        name = convertFilePath(name);
        if (StringUtil.isEmpty(pwd, 6, 20))
            return JsonMessage.getString(400, "请输入6-20的位的密码");
        key = StringUtil.convertNULL(key);
        JSONArray jsonArray;
        try {
            jsonArray = productService.getUserAll(name);
            if (jsonArray == null)
                return JsonMessage.getString(100, "登录失败，没有对应客户信息");
        } catch (IOException e) {
            SystemLog.LOG(LogType.CONTROL_ERROR).error("登录异常", e);
            return JsonMessage.getString(100, "登录异常，没有对应客户信息");
        }
        boolean find = false;
        String pName = null;
        for (int i = jsonArray.size() - 1; i >= 0; i--) {
            JSONObject jsonObject = jsonArray.getJSONObject(i);
            JSONObject object = jsonObject.getJSONObject("oper");
            if (object == null)
                continue;
            String oKey = object.getString("key");
            String oPwd = object.getString("pwd");
            if (key.equals(oKey) && pwd.equals(oPwd)) {
                find = true;
                pName = jsonObject.getString("name");
                break;
            }
        }
        if (find) {
            setSessionAttribute("Oper_User", String.format("%s=%s@%s", key, name, pName));
            return JsonMessage.getString(200, "登录成功");
        }
        return JsonMessage.getString(100, "登录失败");
    }
}
